package club.monkeywood.transaction.order.controller;

import club.monkeywood.transaction.order.dao.OrderRepository;
import club.monkeywood.transaction.order.domain.Order;
import club.monkeywood.transaction.order.dto.OrderDTO;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by mavlarn on 2018/1/20.
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator();

    //@PostConstruct
    //public void init() {
    //    Order order = new Order();
    //    order.setAmount(100);
    //    order.setTitle("MyOrder");
    //    order.setDetail("Bought a imooc course");
    //    orderRepository.save(order);
    //}

    @PostMapping("")
    public void create(@RequestBody OrderDTO orderDTO) {
        orderDTO.setUuid(uuidGenerator.generate().toString());
        amqpTemplate.convertAndSend("order:new", orderDTO);
    }

    @GetMapping("/{id}")
    public OrderDTO getMyOrder(@PathVariable Long id) {
        Order order = orderRepository.findById(id).orElse(null);
        OrderDTO dto = new OrderDTO();
        dto.setId(order.getId());
        dto.setAmount(order.getAmount());
        dto.setTitle(order.getTitle());
        dto.setDetail(order.getDetail());
        return dto;
    }

    @GetMapping("")
    public List<Order> getAll() {
        return orderRepository.findAll();
    }

}
